var socket = undefined;
var cached = new Array(5e3);
var cachedCount = 0;
var firstMessageTime = undefined;
var lastMessageTime = undefined;
function syncWait(e) {
  var a = Date.now();
  while (Date.now() - a < e) {}
}
function createWebsocketWithFallback(e) {
  var a = 0;
  while (a < 10) {
    try {
      return new WebSocket(e);
    } catch (e) {
      syncWait(1e3);
    }
    a++;
  }
  alert("network I/O error");
}
const workerHandler = {
  request: (e, a) => {
    socket.send(JSON.stringify(a.data[2]));
  },
  start: (e, a) => {
    var t = a.data[2];
    var r = a.data[3];
    var n = a.data[4];
    socket = createWebsocketWithFallback(
      "ws://localhost:" + t.toString() + "/" + r + "/" + n
    );
    socket.binaryType = "arraybuffer";
    socket.onopen = () => {
      postMessage([{ t: "onConnected" }]);
    };
    socket.onmessage = (e) => {
      if (!firstMessageTime) {
        firstMessageTime = performance.now();
      }
      lastMessageTime = performance.now();
      var a;
      try {
        var t = new TextDecoder().decode(e.data);
        a = JSON.parse(t);
      } catch (e) {
        debugger;
        alert("webSocketJson: bad json received");
        return;
      }
      a.transferSize = e.data.byteLength;
      cached[cachedCount++] = a;
      if (cachedCount === 5e3) {
        postMessage([{ t: "onResponse", cached: cached }]);
        cached = new Array(5e3);
        cachedCount = 0;
      }
    };
  },
};
setInterval(() => {
  postMessage([
    {
      t: "info",
      data: "info: " + (lastMessageTime - firstMessageTime).toString(),
    },
  ]);
}, 5e3);
onmessage = (e) => {
  var a = e.data[0];
  var t = e.data[1];
  workerHandler[t](a, e);
};
function bufferToBase64Async(e, a) {
  var t = new Blob([e], { type: "application/octet-binary" });
  var r = new FileReader();
  r.onload = function () {
    var e = r.result;
    var t = e.substr(e.indexOf(",") + 1);
    a(t);
  };
  r.readAsDataURL(t);
}
